JavaScript Sorting Arrays

    In the last tutorial, we learned about some of the most important JavaScript array methods and properties, and in this JS tutorial, we will learn how to sort a JS array in ascending and descending order using JS sort() and reverse() method.

    Sort an Array in JavaScript

    To sort an array in JavaScript we can use the array's inbuilt sort() method. The sort() method sorts the array in alphabetically ascending order. The sort() method does not sort the actual array instead it returns a copy of the stored array based on the actual array.

    Example

    <script>
        let cars =["lamborghini","ferrari", "kia", "tesla","hundai"];
        let sorted_cars = cars.sort();
        console.log(sorted_cars);
    </script>

    Output

    ["ferrari", "hundai", "kia", "lamborghini", "tesla"]

    Reverse the Array

    As the name method suggests the reverse() method is used to reverse the order of the array elements. It does not sort the elements in descending order instead it just reverse the order of the array.

    Example

    <script>
    
        let cars =["lamborghini","ferrari", "kia", "tesla","hundai"];
        let reverse_order = cars.reverse();
        console.log(reverse_order);  //["hundai", "tesla", "kia", "ferrari", "lamborghini"]
    
    </script>

    We can also use the reverse() method to sort the array in descending order. To do that first we need to sort the array using sort() method then we can apply the reverse() method on the sorted array to array the elements in descending order. Example

    <script>
        let cars =["lamborghini","ferrari", "kia", "tesla","hundai"];
        let sorted_cars = cars.sort();  // sort in ascending order
        let reverse_order = sorted_cars.reverse(); // reverse the sorted array
    
        console.log(reverse_order);  //["tesla", "lamborghini", "kia", "hundai", "ferrari"]
    </script>

    Sort Numeric Array in JavaScript

    By default, the sort() method converts every array element into a string value so we can not sort a numeric array in a correct format.

    Example

    <script>
        let prices =[12, 32, 10, 55, 100, 102];
        let sorted_prices = prices.sort()
        console.log(sorted_prices)
    </script>

    Output

    [10, 100, 102, 12, 32, 55]

    From the above output, you can see that the sort() method did sort the prices array by converting as an individual string value. According to the string sorting "100" is smaller than "55" becaue the first character of 100 "1" is smaller than the first character of 55 " 5 ". But when it comes to numeric sorting we do not want to sort our numbers as string values, so to fix the above problem we can tweak the sort() method by specifying the function as a parameter.

    Syntax:

    array_name.sort(compare_function)

    Example

    <script>
        let prices =[12, 32, 10, 55, 100, 102];
        let sorted_prices = prices.sort(function(a,b)
                                        {
                                            if(a>b)
                                            {
                                                return 1
                                            }
                                            else if(a==b)
                                            {
                                                return 0;
                                            }
                                            else
                                            {
                                                return -1
                                            }
                                        }
                                        )
        console.log(sorted_prices)
    </script>
    Output
    [10, 12, 32, 55, 100, 102]
    Now our numeric array is sorted correctly. The function statement.
    function(a,b)
        {
        if(a>b)
        {
            return 1
        }
        else if(a==b)
        {
            return 0;
        }
        else
        {
            return -1
        }
    }
    inside the sort() method will sort the array elements in ascending order if you want to arrange the array elements in descending order specify the following function in the sort method.
    <script>
        let prices =[12, 32, 10, 55, 100, 102]; 
        //sort decending
        let sorted_prices = prices.sort(function(a,b)
                                      {
                                            if(a>b)
                                            {
                                                return -1
                                            }
                                            else if(a==b)
                                            {
                                                return 0;
                                            }
                                            else
                                            {
                                                return 1
                                            }
                                        }
                                        )
    
        console.log(sorted_prices)
    </script>
    Output
    [102, 100, 55, 32, 12, 10]

    How does the sort compare function work in JavaScript?

    The function statement we used as a parameter to the sort() method is known as the compare function. The compare function must accept the two arguments(a,b) and can return either negative, positive, or zero value. When the sort() method starts sorting the array values it sends the corresponding values to the comparison function for comparison. And according to the return statement the sort method sort the values. for example, if the sort method send a and b values If the return value is positive a is sorted before b means a is greater than b so it will swap the values. If the return value is negative b is sorted before a means b is greater than a , and it will swap the values. If the return value is 0 means both the values are the same so no swapping would take place.

    Finding Min and Max value in an Array

    JavaScript array does not provide any dedicated min or max method or property that can find out the maximum or minimum value from the array. But there are two simple techniques or logic we can use to find the minimum and maximum value. using sort method To find the minimum or maximum value we can sort the array first and grab the first and last values as minimum or maximum values.

    <script>
        let prices =[12, 32, 10, 55, 100, 102]; 
        let sorted_prices = prices.sort(function(a,b)
                                        {
                                            if(a>b)
                                            {
                                                return 1
                                            }
                                            else if(a==b)
                                            {
                                                return 0;
                                            }
                                            else
                                            {
                                                return -1
                                            }
                                        }
                                        )
    
        minimum = sorted_prices[0]; 
        maximum = sorted_prices[sorted_prices.length-1];
        console.log(minimum);  //10
        console.log(maximum);   //102
    </script>

    The sorted_price[0] will return the first element of the sorted array, and the sorted_prices[sorted_prices.length-1] will return the last element from the sorted array. Using linear logic We can also use linear logic to find out the maximum and minimum values from an array.

    Example

    <script>
        let prices =[12, 32, 10, 55, 100, 102]; 
        maximum= prices[0];
        minimum = prices[0];
        for(let i =0; i<prices.length; i++)
        {
            if(prices[i]> maximum)
            {
                maximum = prices[i];
            }
            if(prices[i]< minimum)
            {
                minimum=prices[i];
            }
        }
        console.log("The minimum value is: "+minimum);
        console.log("The maximum value is: "+maximum);
    </script>
    Output
    The minimum value is: 10
    The maximum value is: 102

    Summary

    • The array's sort() method sorts the array elements in alphabetical order.
    • The reverse() method reverses the order of the array.
    • We can pass the comparison function as a parameter to the sort() sort method, for sorting the numeric values.
    • The comparison function can only return positive, negative, or zero values.

    People are also reading: